import React, { Component } from 'react';
import echarts from 'echarts';
import ReactECharts from 'echarts-for-react';
import { getConfig } from './config';
import 'echarts-gl';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/title';

class AwesomeChart extends Component {
  state = {
    chartRef: null,
    chartInstance: null,
    config: {},
  };

  componentDidMount() {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    this.loadImgAsync('http://p4.music.126.net/nsfjLXC-2yY3j7ZRNtKT4Q==/109951162806843033.jpg?param=200y200')
      .then((img) => {
        const width = img.width / 2;
        canvas.width = width;
        const height = img.height / 2;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);

        const imgData = ctx.getImageData(0, 0, width, height);
        const data = [];

        for (let i = 0; i < imgData.length; i += 1) {
          const r = imgData.data[i * 4];
          const g = imgData.data[i * 4 + 1];
          const b = imgData.data[i * 4 + 2];

          let lum = 255 - (0.2125 * r + 0.7154 * g + 0.0721 * b);
          lum = (lum - 125) / 20 + 50;

          data.push([i % width, height - Math.floor(i / width), lum]);
        }

        this.setState({
          chartRef: React.createRef(),
          config: getConfig(imgData, data),
        });
      })
  }

  componentWillUnmount() {
    const { chartInstance } = this.state;
    // eslint-disable-next-line no-unused-expressions
    chartInstance && chartInstance.dispose();
  }

  // 异步加载图片
  loadImgAsync = url => {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.crossOrigin = 'Anonymous';
      img.onload = () => resolve(img)
      img.onerror = reject

      img.src = url
    })
  }

  renderChart = () => {
    const { chartRef, chartInstance, config } = this.state;

    const renderedInstance = echarts.getInstanceByDom(chartRef.current);
    if (renderedInstance) {
      this.setState({
        chartInstance: renderedInstance,
      });
    } else {
      this.setState({
        chartInstance: echarts.init(chartRef.current),
      });
    }

    chartInstance.setOption(config);
  };

  getOptions = () => { };

  render() {
    const { chartRef } = this.state;
    this.renderChart();

    return <ReactECharts option={this.getOption} lazyUpdate />;
  }
}

export default AwesomeChart;
